<template>
  <div class="app-container">
    <el-dialog :title="id ? '修改' : '新增'" :visible.sync="visible" width="800px" :before-close="handleClose"
      append-to-body :close-on-click-modal="false">
      <el-form ref="form" :model="form" :rules="rules" label-width="100px">
        <el-row>
          <el-col :span="12" class="no">
            <el-form-item label="关联楼层" prop="mapId">
              <el-select v-model="form.mapId" placeholder="请选择楼层" clearable multiple size="small">
                <el-option v-for="dict in floorArr" :key="dict.value" :label="dict.label" :value="dict.value" />
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row v-if="type === 'add' || type === 'edit'">
          <el-col :span="12" class="no">
            <el-form-item label="图书编号" prop="ctrlNo">
              <el-input v-model="form.ctrlNo" :disabled="id ? true : false" />
            </el-form-item>
          </el-col>
        </el-row>
        <div v-if="type === 'add' || type === 'edit'">
          <el-row v-for="(item, index) in ctrlInfoArr" :key="index">
            <el-col :span="4">
              <el-select v-model="item.key" placeholder="请选择标签">
                <el-option v-for="tig in formTemplateData" :key="tig.prop" :label="tig.label" :value="tig.prop">
                </el-option>
              </el-select>
            </el-col>
            <el-col :span="10" class="left">
              <el-form-item :prop="item.prop">
                <el-input v-model="item.val" />
              </el-form-item>
            </el-col>
            <el-col :span="1" class="del">
              <i class="el-icon-delete delcolor" @click="delItem(index)"></i>
            </el-col>
          </el-row>
          <el-row>
            <el-col :offset="8" :span="8" class="add">
              <addButton :contentText="'新增一行表单内容'" @addItem="addItem" />
            </el-col>
          </el-row>
        </div>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="cancle">取 消</el-button>
        <el-button type="primary" @click="sub">确 定</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
import { addBooks, editBooks } from "@/api/books";
import { getfloorArr } from "@/api/map";
import { deepClone } from "@/utils/index";
import { formTemplate } from "./formTemplate";
import { onlyNumberRules } from "@/utils/rules";
import addButton from "@/components/addButton/index.vue";
export default {
  name: "Add",
  components: {
    addButton
  },
  props: {
    id: {
      type: [Number, String],
      default: "",
    },
    visible: {
      type: Boolean,
      default: false,
    },
    objTarget: {
      type: String,
      default: "",
    },
    type: {
      type: String,
      default: "", // add edit bind
    },
  },
  data() {
    // 定义校验规则
    const validateCtrlNo = (rule, value, callback) => {
      if (!value) {
        callback(new Error("图书编号不能为空"));
      } else if (!onlyNumberRules.test(value)) {
        callback(new Error("图书编号只能为数字"));
      } else {
        callback();
      }
    };
    const formTemplateData = formTemplate;
    return {
      formTemplateData: formTemplateData,
      form: {},
      rules: {
        ctrlNo: [
          { required: true, validator: validateCtrlNo, trigger: "blur" },
        ],
      },
      ctrlInfoArr: [],
      addOk: true,
      floorArr: [],
    };
  },
  watch: {
    id: {
      handler(val) {
        if (val) {
          this.giveDetail();
        }
      },
      deep: false,
      immediate: true,
    },
    visible: {
      handler(val) {
        if (val) {
          this.requestfloorArr();
        }
      },
      deep: false,
      immediate: true,
    },
  },
  methods: {
    requestfloorArr() {
      this.floorArr = [];
      getfloorArr(0)
        .then((res) => {
          if (res.success) {
            let arr = res?.data ?? [];
            if (arr.length > 0) {
              arr.map((item) => {
                let obj = {
                  label: item.mapName,
                  value: item.mapId,
                };
                this.floorArr.push(obj);
              });
            }
          }
        })
        .catch((err) => { });
    },
    handleInput(val) {
      this.form.description = val;
    },
    giveDetail() {
      let objTarget = JSON.parse(this.objTarget);
      let ctrlInfo = objTarget?.ctrlInfo ?? [];
      this.ctrlInfoArr = this.dealArr(deepClone(ctrlInfo));
      console.log(this.ctrlInfoArr);
      this.form = {
        ctrlNo: objTarget.ctrlNo,
        mapId: objTarget?.mapId ?? [],
      };
    },
    dealArr(arr) {
      let result = [];
      arr.map((item, index) => {
        // 此处的prop是为了区分不同标签的唯一性，所以需要加上索引
        item.prop = item.key + new Date().getTime();
      });
      result = arr;
      return result;
    },
    cancle() {
      this.handleClose(false);
    },
    delItem(index) {
      const text = "确定删除该图书信息的表单内容?";
      this.$confirm(text, "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      })
        .then(() => {
          this.$message({
            type: "success",
            message: "删除成功!",
          });
          this.ctrlInfoArr.splice(index, 1);
        })
        .catch(() => {
          this.$message({
            type: "info",
            message: "已取消删除",
          });
        });
    },
    addItem() {
      if (this.addOk) {
        let obj = {
          key: "Title",
          val: "",
          prop: "Title" + new Date().getTime(),
        };
        this.ctrlInfoArr.push(obj);
        this.addOk = false;
        setTimeout(() => {
          this.addOk = true;
        }, 100);
      }
    },
    dealSub() {
      let arr = [];
      this.ctrlInfoArr.map((item, index) => {
        arr.push({
          key: item.key,
          val: item.val,
        });
      });
      return arr;
    },
    sub() {
      // 触发表单校验
      this.$refs.form.validate((valid) => {
        if (valid) {
          // 校验通过，执行提交逻辑
          let requestWay, msg, errmsg;
          let queryParams = {
            ctrlNo: this.form.ctrlNo,
            mapId: this.form.mapId,
          };
          if (this.id) {
            requestWay = editBooks;
            queryParams.ctrlId = this.id;
            msg = "修改成功";
            errmsg = "修改失败";
          } else {
            requestWay = addBooks;
            msg = "新增成功";
            errmsg = "新增失败";
          }
          queryParams.ctrlInfo = this.dealSub();
          // console.log("提交表单数据:", queryParams);
          requestWay(queryParams)
            .then((res) => {
              if (res.success) {
                this.$message.success(msg);
                this.handleClose(true);
              } else {
                this.$message.error(errmsg);
              }
            })
            .catch((err) => {
              console.log(err);
            });
        } else {
          console.log("表单校验未通过");
          return false;
        }
      });
    },
    handleClose(status) {
      this.form = {};
      // 重置表单
      this.$refs.form.resetFields();
      this.ctrlInfoArr = [];
      this.$emit("update:visible", false);
      this.$emit("close", status === true ? status : false);
    },
  },
};
</script>

<style lang="scss" scoped>
.left {
  .el-input {
    width: 280px;
    margin-left: -90px;
  }
}

.no {
  margin-left: 35px;
}

.del {
  height: 36px;
  display: flex;
  align-items: center;
  justify-content: center;

  .el-icon-delete {
    cursor: pointer;
    font-size: 16px;
  }
}

.add {
  height: 36px;
  display: flex;
  align-items: center;
  justify-content: center;
}
</style>
